package com.zhihaoliang.baseframe.ui;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.zhihaoliang.baseframe.R;
import com.zhihaoliang.baseframe.databinding.FragmentProductBinding;
import com.zhihaoliang.baseframe.viewmodel.ProductViewModel;

/**
 * 创建日期：2020-02-26
 * 描述:产品详情的Fragment
 * 作者:支豪亮
 */
public class ProductFragment extends Fragment {
    public static final String TAG = "ProductFragment";

    private static final String KEY_PRODUCT_ID = "product_id";

    private FragmentProductBinding mBinding;

    private CommentAdapter mCommentAdapter;

    private final CommentClickCallback mCommentClickCallback = comment -> {
        Log.e("===", "Comment 点击操作");
    };

    public static ProductFragment forProduct(int productId) {
        ProductFragment productFragment = new ProductFragment();
        Bundle args = new Bundle();
        args.putInt(KEY_PRODUCT_ID, productId);
        productFragment.setArguments(args);
        return productFragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_product, container, false);
        mCommentAdapter = new CommentAdapter(mCommentClickCallback);
        mBinding.commentList.setAdapter(mCommentAdapter);
        return mBinding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ProductViewModel.Factory factory = new ProductViewModel.Factory(requireActivity().getApplication(),
                requireArguments().getInt(KEY_PRODUCT_ID));

        final ProductViewModel model = new ViewModelProvider(this,factory).get(ProductViewModel.class);
        subscribeToModel(model);
    }

    private void subscribeToModel(final ProductViewModel model){
        model.getComments().observe(getViewLifecycleOwner(),commentEntities -> {
            if(commentEntities == null){
                mBinding.setIsLoading(true);
            }else{
                mBinding.setIsLoading(false);
                mCommentAdapter.submitList(commentEntities);
            }
        });
    }
}
